package com.example.bbang.Interceptor;

import com.example.bbang.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.bind.annotation.RequestAttribute;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * 自定义拦截器类
 */
public class UserInterceptor implements HandlerInterceptor {// 实现HandlerInterceptor接口
    /**
     * 访问控制器方法前执行
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        //当前时间和请求
        System.out.println(new Date() + "--preHandle:" + request.getRequestURL());
        System.out.println("userSession33333"+request.getServletContext().getAttribute("User"));
        // 获取Session
        User user = (User) request.getServletContext().getAttribute("User");//获取USER_SESSION的属性
        System.out.println("usercontroller:"+user);
        // 判断Session中是否有用户数据，如果有，则返回true,继续向下执行
        if(user == null) {
            System.out.println("--没有登陆" );
            return false;

        }
        System.out.println("--登陆了" );
       return true;
    }

    /**
     * 访问控制器方法后执行
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
      //  System.out.println(new Date() + "--postHandle:" + request.getRequestURL());
    }

    /**
     * postHandle方法执行完成后执行，一般用于释放资源
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
     //   System.out.println(new Date() + "--afterCompletion:" + request.getRequestURL());
    }
}
